import 'dart:io';

import 'package:appupgrade/app_market.dart';
import 'package:appupgrade/appupgrade_platform_interface.dart';
import 'package:dio/dio.dart';
import 'package:path_provider/path_provider.dart';
import 'package:flutter/material.dart';
import 'package:appupgrade/appupgrade.dart';
import 'package:appupgrade/download_status.dart';
import 'package:url_launcher/url_launcher.dart';
import 'liquid_progress_indicator.dart';

///
/// des:app升级提示控件
///
class SimpleAppUpgradeWidget extends StatefulWidget {
  static OverlayEntry? currentEntry;

  ///
  /// 升级标题
  ///
  String? title;

  ///
  /// 标题样式
  ///
  TextStyle? titleStyle;

  ///
  /// 升级提示内容
  ///
  final List<String> contents;

  ///
  /// 提示内容样式
  ///
  TextStyle? contentStyle;

  ///
  /// 进度条颜色
  ///
  Color? progressBarColor;

  ///
  /// 确认控件
  ///
  String? okText;

  ///
  /// 确认控件样式
  ///
  TextStyle? okTextStyle;

  ///
  /// 确认控件背景颜色
  ///
  final Color? okBackgroundColor;

  ///
  /// 取消控件
  ///
  String? cancelText;

  ///
  /// 取消控件样式
  ///
  TextStyle? cancelTextStyle;

  ///
  /// app安装包下载url,没有下载跳转到应用宝等渠道更新
  ///
  String? downloadUrl;

  String? downloadSavePath;

  ///
  /// 圆角半径
  ///
  final double borderRadius;

  ///
  /// 是否强制升级,设置true没有取消按钮
  ///
  final bool force;

  ///
  /// ios app id,用于跳转app store
  ///
  final String iosAppId;

  ///
  /// 指定跳转的应用市场，
  /// 如果不指定将会弹出提示框，让用户选择哪一个应用市场。
  ///
  final AppMarketInfo appMarketInfo;

  VoidCallback? onCancel;
  VoidCallback? onOk;
  DownloadProgressCallback? downloadProgress;
  DownloadStatusChangeCallback? downloadStatusChange;

  SimpleAppUpgradeWidget(
      {this.title,
      this.titleStyle,
      required this.contents,
      this.contentStyle,
      this.cancelText,
      this.cancelTextStyle,
      this.okText,
      this.okTextStyle,
      this.okBackgroundColor = Colors.blue,
      this.progressBarColor,
      this.borderRadius = 3,
      required this.downloadUrl,
      this.downloadSavePath,
      this.force = false,
      required this.iosAppId,
      required this.appMarketInfo,
      this.onCancel,
      this.onOk,
      this.downloadProgress,
      this.downloadStatusChange});

  @override
  State<StatefulWidget> createState() => _SimpleAppUpgradeWidget();
}

class _SimpleAppUpgradeWidget extends State<SimpleAppUpgradeWidget> {
  CancelToken token = CancelToken();

  ///
  /// 下载进度
  ///
  double _downloadProgress = 0.0;

  DownloadStatus _downloadStatus = DownloadStatus.none;

  @override
  Widget build(BuildContext context) {
    return Material(
        type: MaterialType.transparency,
        child: Container(
          alignment: Alignment.center,
          color: Colors.black12,
          child: Container(
            width: MediaQuery.of(context).size.width < 360
                ? MediaQuery.of(context).size.width - 20
                : 360,
            alignment: Alignment.center,
            child: Stack(children: <Widget>[
              _buildInfoWidget(context),
              _downloadProgress > 0
                  ? Positioned.fill(child: _buildDownloadProgress())
                  : Container(
                      height: 10,
                    )
            ]),
          ),
        ));
  }

  ///
  /// 信息展示widget
  ///
  Widget _buildInfoWidget(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.all(Radius.circular(widget.borderRadius)),
        color: Colors.white,
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          //标题
          _buildTitle(),
          //更新信息
          _buildAppInfo(),
          //操作按钮
          _buildAction()
        ],
      ),
    );
  }

  ///
  /// 构建标题
  ///
  _buildTitle() {
    return Padding(
        padding: EdgeInsets.only(top: 20, bottom: 30),
        child: Text(widget.title ?? '',
            style: widget.titleStyle ?? TextStyle(fontSize: 22)));
  }

  ///
  /// 构建版本更新信息
  ///
  _buildAppInfo() {
    return Container(
        padding: EdgeInsets.only(left: 15, right: 15, bottom: 30),
        height: 200,
        child: ListView(
          children: widget.contents.map((f) {
            return Text(
              f,
              style: widget.contentStyle ?? TextStyle(),
            );
          }).toList(),
        ));
  }

  ///
  /// 构建取消或者升级按钮
  ///
  _buildAction() {
    return Column(
      children: <Widget>[
        Divider(
          height: 1,
          color: Colors.grey,
        ),
        Row(
          children: <Widget>[
            widget.force
                ? Container()
                : Expanded(
                    child: _buildCancelActionButton(),
                  ),
            Expanded(
              child: _buildOkActionButton(),
            ),
          ],
        ),
      ],
    );
  }

  ///
  /// 取消按钮
  ///
  _buildCancelActionButton() {
    return Container(
      decoration: BoxDecoration(
          borderRadius: BorderRadius.only(
              bottomLeft: Radius.circular(widget.borderRadius))),
      child: InkWell(
          borderRadius: BorderRadius.only(
              bottomLeft: Radius.circular(widget.borderRadius)),
          child: Container(
            height: 45,
            alignment: Alignment.center,
            child: Text(widget.cancelText ?? '以后再说',
                style: widget.cancelTextStyle ?? TextStyle()),
          ),
          onTap: () {
            widget.onCancel?.call();
            SimpleAppUpgradeWidget.currentEntry?.remove();
          }),
    );
  }

  ///
  /// 确定按钮
  ///
  _buildOkActionButton() {
    var borderRadius =
        BorderRadius.only(bottomRight: Radius.circular(widget.borderRadius));
    if (widget.force) {
      borderRadius = BorderRadius.only(
          bottomRight: Radius.circular(widget.borderRadius),
          bottomLeft: Radius.circular(widget.borderRadius));
    }
    var _okBackgroundColor = widget.okBackgroundColor ?? Colors.blue;
    return Container(
      decoration: BoxDecoration(
        borderRadius: borderRadius,
        color: _okBackgroundColor,
      ),
      child: InkWell(
        borderRadius: borderRadius,
        child: Container(
          height: 45,
          alignment: Alignment.center,
          child: Text(widget.okText ?? '立即体验',
              style: widget.okTextStyle ?? TextStyle(color: Colors.white)),
        ),
        onTap: () {
          _clickOk();
        },
      ),
    );
  }

  ///
  /// 下载进度widget
  ///
  Widget _buildDownloadProgress() {
    return LiquidLinearProgressIndicator(
      value: _downloadProgress,
      direction: Axis.vertical,
      backgroundColor: Colors.black12,
      borderWidth: 1,
      borderColor: Colors.blue,
      valueColor: AlwaysStoppedAnimation(widget.progressBarColor ??
          Theme.of(context).primaryColor.withOpacity(0.4)),
      borderRadius: widget.borderRadius,
      close: () {
        token.cancel("canceled");
        widget.onCancel?.call();
        SimpleAppUpgradeWidget.currentEntry?.remove();
      },
    );
  }

  ///
  /// 点击确定按钮
  ///
  _clickOk() async {
    widget.onOk?.call();
    if (Platform.isIOS) {
      //ios 需要跳转到app store更新，原生实现
      AppupgradePlatform.instance.toAppStore(widget.iosAppId);
      return;
    }
    if (widget.downloadUrl == null || widget.downloadUrl!.isEmpty) {
      //没有下载地址，跳转到第三方渠道更新，原生实现
      AppupgradePlatform.instance.toMarket(appMarketInfo: widget.appMarketInfo);
      return;
    }
    if (widget.downloadSavePath != null) {
      _downloadApk(widget.downloadUrl!, widget.downloadSavePath!);
    } else {
      String filename = widget.downloadUrl!
          .substring(widget.downloadUrl!.lastIndexOf('/') + 1);
      if (Platform.isAndroid) {
        Directory? tempDir = await getExternalStorageDirectory();
        String path = tempDir!.path;
        _downloadApk(widget.downloadUrl!, '$path/$filename');
      } else {
        Directory? tempDir = await getTemporaryDirectory();
        String path = tempDir.path;
        print(path);
        _downloadApk(widget.downloadUrl!, '$path/$filename');
      }
    }
  }

  ///
  /// 下载apk包
  ///
  _downloadApk(String url, String path) async {
    print("url ${url} /n cache path ${path}");
    if (_downloadStatus == DownloadStatus.start ||
        _downloadStatus == DownloadStatus.downloading ||
        _downloadStatus == DownloadStatus.done) {
      print('当前下载状态：$_downloadStatus,不能重复下载。');
      return;
    }

    _updateDownloadStatus(DownloadStatus.start);
    try {
      var dio = Dio();
      await dio.download(url, path, cancelToken: token,
          onReceiveProgress: (int count, int total) async {
        if (total == -1) {
          _downloadProgress = 0.01;
        } else {
          widget.downloadProgress?.call(count, total);
          _downloadProgress = count / total.toDouble();
        }
        setState(() {});
        if (_downloadProgress == 1) {
          //下载完成，跳转到程序安装界面
          _updateDownloadStatus(DownloadStatus.done);
          Navigator.pop(context);
          if (Platform.isAndroid) {
            AppupgradePlatform.instance.installAppForAndroid(path);
          } else if (Platform.isWindows) {
            await AppupgradePlatform.instance.installAppForWindows(path);
            //关闭当前应用程序
            exit(0);
          } else if (Platform.isMacOS) {
            print(path);
            String res =
                await AppupgradePlatform.instance.installAppForMac(path);
            print(res);
            //关闭当前应用程序
            exit(0);
          } else {
            Directory? tempDir = await getTemporaryDirectory();
            launchUrl(Uri.file("file://${tempDir.path}"));
          }
        }
      });
    } catch (e) {
      print('$e');
      _downloadProgress = 0;
      _updateDownloadStatus(DownloadStatus.error, error: e);
    }
  }

  _updateDownloadStatus(DownloadStatus downloadStatus, {dynamic error}) {
    _downloadStatus = downloadStatus;
    widget.downloadStatusChange?.call(_downloadStatus, error: error);
  }
}
